<?php

namespace app\admin\controller;

use think\Request;
use think\Exception;
use app\common\controller\Common;
use think\addons\PluginService;
use think\facade\View;
use think\facade\Session;
use think\facade\Db;

/**
 * 插件控制器
 */
class Plugins extends Common
{
    const apiurl = 'https://kefu.69kz.com/';
    const fixed = 'api';
    /**
     * 插件列表
     * @return plugin_lists
     */
    public function plugin_lists()
    {
        return View::fetch();
    }

    /**
     * 上传本地插件
     * @return plugin_upload
     */
    public function plugin_upload(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            if (!empty($_FILES['upload_plugin']['tmp_name'])) {
                try {
                    $info = PluginService::local($r->file('upload_plugin'));
                    return json([
                        'code' => 200,
                        'data' => $info['title'] . '上传成功',
                        'url'  => adminUrl('admin/Plugins/plugin_lists')
                    ]);
                } catch (AddonException $e) {
                    return json(['code' => 300, 'data' => $e->getMessage()]);
                } catch (Exception $e) {
                    return json(['code' => 300, 'data' => $e->getMessage()]);
                }
            }
        }

        return View::fetch();
    }

    /**
     * 禁用启用
     */
    public function plugin_state(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $name   = $r->post('name');
            $action = $r->post('action');
            $action = $action == 'enable' ? $action : 'disable';
            try {
                // 调用启用、禁用的方法
                $info = PluginService::$action($name);
                if ($info) {
                    return json([
                        'code' => 200,
                        'data' => '更改成功'
                    ]);
                }
            } catch (AddonException $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            } catch (Exception $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            }
        }
    }

    /**
     * 卸载删除插件
     */
    public function plugin_uninstall(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            try {
                $info = PluginService::uninstall($r->post('name', ''));
                if ($info) {
                    return json([
                        'code' => 200,
                        'data' => '卸载成功'
                    ]);
                }
            } catch (AddonException $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            } catch (Exception $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            }
        }
    }

    /**
     * 插件配置
     */
    public function plugin_config(Request $r)
    {
        $name = null;
        $name = $name ? $name : $r->get('name');
        if (!$name) {
            return json(['code' => 300, 'data' => 'name参数不能是空的']);
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            return json(['code' => 300, 'data' => '插件名称不正确']);
        }
        if (!is_dir(root_path() . 'addons/' . $name)) {
            return json(['code' => 300, 'data' => '目录未找到']);
        }
        $info = get_addons_info($name);
        $config = get_addons_config($name);
        if (!$info) {
            return json(['code' => 300, 'data' => '没有找到结果']);
        }

        if ($r->isAjax() && $r->isPost()) {
            $params = $r->post("row/a", [], 'trim');
            if ($params) {
                $params_lists = [];
                foreach ($params as $key => $item) {
                    if (is_array($item)) {
                        foreach ($item as $key2 => $item2) {
                            if (is_array($item2)) {
                                if (!empty($item2['key'])) {
                                    $params_lists[$key][$item2['key']] = empty($item2['value'])?'':$item2['value'];
                                } else {
                                    $params_lists[$key][''] = empty($item2['value'])?'':$item2['value'];
                                }
                            } else {
                                $params_lists[$key][$key2] = $item2;
                            }
                        }
                        if (is_assoc($params_lists[$key])) {
                            $params_lists[$key] = json_encode($params_lists[$key]);
                        }
                    } else {
                        $params_lists[$key] = $item;
                    }
                }

                foreach ($config as $k => &$v) {
                    if (isset($params_lists[$v['name']])) {
                        if ($v['type'] == 'array') {
                            $params_lists[$v['name']] = is_array($params_lists[$v['name']]) ? $params_lists[$v['name']] : (array)json_decode($params_lists[$v['name']], true);
                            $value = $params_lists[$v['name']];
                        } else {
                            $value = is_array($params_lists[$v['name']]) ? implode(',', $params_lists[$v['name']]) : $params_lists[$v['name']];
                        }
                        if ($v['type'] == 'editor_array') {
                            $v['value'] = json_decode($value, true);
                        } else {
                            $v['value'] = $value;
                        }
                    }
                }

                try {
                    //更新配置文件
                    set_addons_fullconfig($name, $config);
                    return json(['code' => 200, 'data' => '更改成功']);
                } catch (\Exception $e) {
                    return json(['code' => 300, 'data' => $e->getMessage()]);
                }
            }

            return json(['code' => 300, 'data' => '参数不能是空的']);
        }

        $tips = [];
        foreach ($config as $index => &$item) {
            if ($item['name'] == '__tips__') {
                $tips = $item;
                unset($config[$index]);
            }
        }
        View::assign('addon', [
            'info'   => $info,
            'config' => $config,
            'tips'   => $tips
        ]);
        $configFile = root_path() . 'addons/' . $name . DIRECTORY_SEPARATOR . 'config.html';
        $viewFile = is_file($configFile) ? $configFile : '';
        return View::fetch($viewFile);
    }
    // 插件市场
    public function plugin_market(Request $r){
        $plist = [];
        $msg = '';
        $pcount = 0;
        $is_auth = 1;
        $is_login = 1;
        $nhost = self::apiurl.'api.php/notice';
        $narr = [];
        $nheader = array('HTTP/1.1 200 OK');
        $nreturn = curlPost($nhost, $narr, 5, $nheader, 'array');
        $nres = (array)json_decode($nreturn);
        $db = Db::name('im_market')->where(['url' => $_SERVER['HTTP_HOST']])->find();
        if($db != ''){// 直接进入
            $header = array('HTTP/1.1 200 OK');
            $is_login = 2;
            $chost = self::apiurl.'api.php/curl';// 查询授权
            $cdata = ['realname' => $_SERVER['HTTP_HOST'], 'signature' => strtoupper(md5(sha1($db['key']))), 'sid' => self::decrypt($db['secret'], self::apiurl)];
            $creturn = curlPost($chost, $cdata, 5, $header, 'array');
            $cres = (array)json_decode($creturn);
            if($cres['code'] == 200){
                Session::set('yes_apply', 1);
                $phost = self::apiurl.'api.php/plist';// 插件列表
                $header = array('HTTP/1.1 200 OK');
                $pdata = ['realname' => $_SERVER['HTTP_HOST'], 'signature' => strtoupper(md5(sha1($db['key']))), 'sid' => self::decrypt($db['secret'], self::apiurl)];
                $preturn = curlPost($phost, $pdata, 5, $header, 'array');
                $pres = (array)json_decode($preturn);
                if($pres['code'] == 200){
                    if(count($pres['data']) > 0){
                        $pcount = count($pres['data']);
                        $plist[] = $pres['data'];
                    }else{
                        $msg = $pres['msg'];
                    }
                }else{
                    $msg = $pres['msg'];
                }
            }else{
                Session::delete('yes_apply');
                $msg = $cres['msg'];
                if($cres['code'] == 300){
                    $is_login = 1;
                    Session::delete('login_status');
                }
            }
        }else{
            Session::delete('login_status');
            $msg = '请登录插件平台';
        }
        if(Session::has('yes_apply'))
            $is_auth = 2;
        if(Session::has('login_status'))
            $is_login = 2;
        if(Session::has('to_apply')){
            $is_login = 1;
            $msg = '请登录申请此域名的插件平台账号';
        }
        // ajax 开始
        if ($r->isAjax() && $r->isPost()) {// 点击
            $account = trim($r->post('plogin'));
            $pwd = trim($r->post('ppwd'));
            if($account == '' || $pwd == '')
                return json(['code' => 300, 'data' => '缺少参数哦']);
            $host = self::apiurl.'api.php/clogin';
            $data = ['account' => $account, 'pwd' => $pwd, 'fixed' => self::fixed];
            $header = array('HTTP/1.1 200 OK');
            $return = curlPost($host, $data, 5, $header, 'array');
            $res = (array)json_decode($return);
            if($res['code'] != 200)
                return json(['code' => 300, 'data' => $res['msg']]);
            if($res['data']->accesskey == '' || $res['data']->sid == '')
                return json(['code' => 300, 'data' => '请求出错']);
            $chost = self::apiurl.'api.php/curl';// ajax 查询授权
            $cdata = ['realname' => $_SERVER['HTTP_HOST'], 'signature' => strtoupper(md5(sha1($res['data']->accesskey))), 'sid' => $res['data']->sid];
            $creturn = curlPost($chost, $cdata, 5, $header, 'array');
            $cres = (array)json_decode($creturn);
            $db = Db::name('im_market')->where(['url' => $_SERVER['HTTP_HOST']])->find();
            $marr = ['url' => $_SERVER['HTTP_HOST'], 'account' => $account, 'pwd' => self::encrypt($pwd, self::apiurl), 'key' => $res['data']->accesskey, 'secret' => self::encrypt($res['data']->sid, self::apiurl), 'create_time' => time()];
            if($db == ''){
                Db::name('im_market')->save($marr);
            }else{
                Db::name('im_market')->where('id', $db['id'])->update($marr);
            }
            if($cres['code'] == 200){
                Session::set('yes_apply', 1);
                $phost = self::apiurl.'api.php/plist';// ajax 插件列表
                $pdata = ['realname' => $_SERVER['HTTP_HOST'], 'signature' => strtoupper(md5(sha1($res['data']->accesskey))), 'sid' => $res['data']->sid];
                $preturn = curlPost($phost, $pdata, 5, $header, 'array');
                $pres = (array)json_decode($preturn);
                if($pres['code'] != 200){
                    return json(['code' => 300, 'data' => $pres['msg']]);
                }
                Session::delete('to_apply');
                return json(['code' => 200, 'data' => '请求成功']);
            }else{
                Session::set('login_status', 1);
                if(Session::has('to_apply')){
                    return json(['code' => 200, 'data' => '请登录申请此域名的插件平台账号']);
                }
                return json(['code' => 200, 'data' => '请申请域名授权']);
            }
        }
        // ajax 结束
        return view('plugin_market', [
            'pcount' => $pcount,
            'plist' => $plist,
            'msg' => $msg,
            'is_login' => $is_login,
            'is_auth' => $is_auth,
            'price' => $nres['data']->price,
        ]);
    }
    // 请申请授权
    public function plugin_apply(Request $r){
        if($r->post('pay') != 1 && $r->post('pay') != 2)
            return json(['code' => 300, 'data' => '参数错误']);
        $db = Db::name('im_market')->where(['url' => $_SERVER['HTTP_HOST']])->find();
        if($db != ''){
            $host = self::apiurl.'api.php/rauth';// 申请授权
            $data = ['realname' => $_SERVER['HTTP_HOST'], 'signature' => strtoupper(md5(sha1($db['key']))), 'sid' => self::decrypt($db['secret'], self::apiurl), 'ptype' => trim($r->post('pay'))];
            $header = array('HTTP/1.1 200 OK');
            $return = curlPost($host, $data, 5, $header, 'array');
            $res = (array)json_decode($return);
            if($res['code'] == 200){
                Session::set('yes_apply', 1);
                return json(['code' => 200, 'data' => '申请成功']);
            }else{
                if($res['code'] == 300){
                    Session::delete('login_status');
                }else{
                    if($res['code'] == 600){
                        Session::delete('login_status');
                        Session::set('to_apply', 1);
                        return json(['code' => 200, 'data' => $res['msg']]);
                    }
                    return json(['code' => 300, 'data' => $res['msg']]);
                }
            }
        }else{
            Session::delete('login_status');
            return json(['code' => 200, 'data' => '请登录插件平台']);
        }
    }
    // 安装
    public function plugin_install(Request $r){
        if($r->post('pid') == '' || $r->post('url') == '')
            return json(['code' => 300, 'data' => '参数错误']);
        $db = Db::name('im_market')->where(['url' => $_SERVER['HTTP_HOST']])->find();
        if($db != ''){
            $host = self::apiurl.'api.php/pinstall';// 安装插件
            $data = ['durl' => trim($r->post('url')) , 'signature' => strtoupper(md5(sha1($db['key']))), 'sid' => self::decrypt($db['secret'], self::apiurl)];
            $header = array('HTTP/1.1 200 OK');
            $return = curlPost($host, $data, 5, $header, 'array');
            $res = (array)json_decode($return);
            if($res['code'] != 200)
                return json(['code' => 300, 'data' => $res['msg']]);
            try {
                $info = PluginService::longinstall($res['data']->zurl);
                return json([
                    'code' => 200,
                    'data' => $info['title'] . '上传成功',
                    'url'  => adminUrl('admin/Plugins/plugin_lists')
                ]);
            } catch (AddonException $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            } catch (Exception $e) {
                return json(['code' => 300, 'data' => $e->getMessage()]);
            }
        }else{
            Session::delete('login_status');
            return json(['code' => 400, 'data' => '请登录插件平台']);
        }
    }
    // 加密
    public function encrypt($data, $key) {
       $data =  openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
       return base64_encode($data);
    }
    // 解密
    public function decrypt($data, $key) {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
    }
}